import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.ServerSocket;


public class Server {
	
	static String host;
	static int port = 50000;
	static ServerSocket listener;
	static Socket serverSocket;
	static String inputLine, outputLine;
	static BufferedReader in;

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// we instantiate the server socket
		try {
			listener = new ServerSocket(port);
		} catch (IOException e) {
			System.out.println("Could not listen on port: " + 50);
		    System.exit(-1);
		}
		
		// we accept the connection and bind it to a socket
		System.out.println("Server initialized: waiting for connection");
		try {
			serverSocket = listener.accept();
		} catch (IOException e) {
			System.out.println("Accept failed");
		    System.exit(-1);
		}
		
		// we link the input stream to a buffered reader
		in = new BufferedReader(new InputStreamReader(serverSocket.getInputStream()));

		System.out.println("Connection established: waiting for messages from client");
		
		while ((inputLine = in.readLine()) != null ) {   
		    System.out.println("Msg: " + inputLine);
		    if (inputLine.equalsIgnoreCase("exit"))
		    	break;
		}	
		
		if(serverSocket != null)
			serverSocket.close();
		if(in != null)
			in.close();
		if(listener != null)
			listener.close();
		
		System.out.println("Program exited properly");
	}
}
